package com.car.action.api;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import com.alibaba.fastjson.JSONObject;
import com.car.action.util.CommonController;
import com.car.common.model.Message;
import com.car.common.model.MessageUnreadNum;
import com.car.common.model.UserFriends;
import com.car.common.model.UserWatch;
import com.car.common.model.Users;
import com.car.common.model.UsersInfo;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.utils.APIJSON;
import com.utils.PicUtil;
import com.utils.RongCloudUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;

public class ImController  extends CommonController {

    /**
     * 获取聊天token
     */
    public void get_token() {
    	String message = check_user(false);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			Db.update("update users set login_status = 0 where id = " + user_id); 
			UsersInfo info = UsersInfo.dao.findFirst("select im_token from users_info where user_id = " + user_id);
			if (info == null || StringUtil.empty(info.getImToken())) {
				Users users = Users.dao.findById(user_id);
				if (users != null ) {
					/**
					 * 
					 userId	String	用户 Id，支持大小写英文字母、数字、部分特殊符号 + = - _ 的组合方式，最大长度 64 字节。是用户在 App 中的唯一标识，必须保证在同一个 App 内不重复，重复的用户 Id 将被当作是同一用户。（必传）
					 name	String	用户名称，最大长度 128 字节。用来在 Push 推送时显示用户的名称。（必传）
					 portraitUri	String	用户头像 URI，最大长度 1024 字节。（必传）
					 */
					Map<String, String> params = Maps.newHashMap();
					params.put("userId",   		String.valueOf(user_id));
					params.put("name",     		StringUtil.empty(users.getNickName())?"火星人": users.getNickName());
					if (StringUtil.empty(users.getUserHeader())) {
						params.put("portraitUri",     PicUtil.DEFAULT_HEAD);
					} else {
						params.put("portraitUri",     PicUtil.QINIU_DIR +  users.getUserHeader());
					}
					JSONObject jsonObject = RongCloudUtil.post("http://api-cn.ronghub.com/user/getToken.json", params);
					if (jsonObject.getIntValue("code") == 200) {
						
						String token = jsonObject.getString("token");
						
						Db.update("update users_info set im_token = '" + token + "' where user_id = " + user_id); 
						Map<String,Object> result = Maps.newHashMap();
						result.put("token", token);
						renderText(APIJSON.send(result));
					}
				}
			} else {
				Map<String,Object> result = Maps.newHashMap();
				result.put("token", info.get("im_token"));
				renderText(APIJSON.send(result));
			}
		}
    }
    
    /**
     * 发送消息前检查
     */
    public void send_check() {
    	String message = check_user(false);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			if (StringUtil.empty(getPara("target_user_id")) ) {
				renderText(APIJSON.result(4001));
				return;
			}
			Long user_id = super.getUserId();
			int target_user_id = getParaToInt("target_user_id");
			
			if(user_id == 141 || user_id == 200 ) {
				renderText(APIJSON.result(0));
				return;
			}
			if(target_user_id == 141 || target_user_id == 200 ) {
				renderText(APIJSON.result(0));
				return;
			}
			// 1 好友关系 
			UserFriends one = UserFriends.dao.findFirst("select id from user_friends where ((user_id = "+ user_id +" and target_user_id = " + target_user_id +") or (user_id = "+ target_user_id + " and target_user_id = " + user_id +") ) and status = 1 and delete_time is null order by id desc limit 1 ");
			if(one != null) {
				renderText(APIJSON.result(0));
				return;
			} else {
			// 2 守护关系  user_id 守护  target_user_id
				UserWatch guard = UserWatch.dao.findFirst("select id from user_watch where  (user_id = " + target_user_id +" and target_user_id = " + user_id +") or (user_id = " + user_id +" and target_user_id = " + target_user_id +")");
				if (guard != null) {
					renderText(APIJSON.result(0));
					return;
				}
			// 3 自己拥有畅聊徽章 ，不限制	
				Users me = Users.dao.findById(user_id);
				if (me.getInt("talk_badge") > 0  && me.getLong("talk_end_time").longValue() > SystemClock.now()/1000L) {
					renderText(APIJSON.result(0));
					return;
				}
				
				Message  im_message  = Message.dao.findFirst("select * from message where fromUserId = " + target_user_id + " and toUserId = " + user_id + " and channelType ='PERSON' and msgTimestamp > " + (SystemClock.now() - 12 * 60 * 60 * 1000L));
				if (im_message != null) {
					Users you = Users.dao.findById(target_user_id);
					if (you.getInt("talk_badge") > 0  && you.getLong("talk_end_time").longValue() > SystemClock.now()/1000L) {
						// 4 target_user_id 对方拥有畅聊徽章  ，自己加好友		
						one = new UserFriends();
						one.setUserId(user_id.intValue());
						one.setTargetUserId(target_user_id);
						one.setStatus(1);
						one.setCreateTime(SystemClock.now()/1000L);
						one.setUpdateTime(SystemClock.now()/1000L);
						if (one.save()) {
							MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FRIEND, target_user_id);
						}
						renderText(APIJSON.result(0));
						return;
					}
				}
				renderText(APIJSON.result(1083));
				return;
			}
			

			
		}
    }
    
    
    public void clean() {
    	List<Users> users = Users.dao.find("select id,nick_name from users where nick_name is not null and LENGTH(nick_name) > 0  ");
    	for(Users one :users) {
    		try {
    			String nick_name = StringUtil.decode(one.getNickName()); 
        		if (nick_name.indexOf("�") > -1) {
        			nick_name = nick_name.replaceAll("�", "");
            		System.out.println("update users set nick_name = '" + nick_name +"' where id =" +one.getId());
            		Db.update("update users set nick_name = '" + StringUtil.encode(nick_name) +"' where id =" +one.getId());
        		}
    		} catch (Exception e) {
			}
    		
//    		System.out.println();
    	}
    	
    	renderText("操作成功!");
    }
    
    
    public void create_mq() throws JMSException, IOException {
    	//47.101.62.242
    	 // 创建一个ConnectionFactory对象连接MQ服务器
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
        // 创建一个连接对象
        Connection connection;
        connection = connectionFactory.createConnection();
        // 开启连接
        connection.start();
        // 使用Connection对象创建一个Session对象
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 创建一个Destination对象。topic对象
        Topic topic = session.createTopic("test-topic");
        // 使用Session对象创建一个消费者对象。
        MessageConsumer consumer = session.createConsumer(topic);
        // 接收消息
        consumer.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(javax.jms.Message message) {
                // 打印结果
                TextMessage textMessage = (TextMessage) message;
                String text;
                try {
                    text = textMessage.getText();
                    System.out.println("这是接收到的消息：" + text);
                } catch (JMSException e) {
                    e.printStackTrace();
                }

            }
        });
        System.out.println("topic消费者启动。。。。");
        // 等待接收消息
        System.in.read();
        // 关闭资源
        consumer.close();
        session.close();
        connection.close();
    }
    
    public static void main(String[] args) {
		try {
			new ImController().create_mq();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
